package com.red.wood.module.eval.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ModelAndView;

import com.red.wood.common.domain.Page;
import com.red.wood.common.springjdbc.SqlServerDao;
import com.red.wood.common.util.CommonUtils;
import com.red.wood.common.util.IMap;
import com.red.wood.common.util.SysProps;
import com.red.wood.module.eval.mybatis.service.EvalResultInfoService;

import net.sf.json.JSONObject;

@Controller
@RequestMapping("/evalResultInfo")
public class EvalResultInfoController {
	
	private static final Log log = LogFactory.getLog(EvalResultInfoController.class);
	
	@Autowired
	private EvalResultInfoService service;

	@Autowired
	private SqlServerDao sqlServerDao;
	
	/**
	 * 评测通过企业
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping
	public ModelAndView index(HttpServletRequest request, HttpServletResponse response){
		String type = request.getParameter("type");
		ModelAndView mv = new ModelAndView("evalResultInfo");
		if(StringUtils.equals(type, "oper")) {
			mv = new ModelAndView("eval_result");
		}else if(StringUtils.equals(type, "upload")) {
			mv.addObject("evalNum",CommonUtils.valueOf(request.getParameter("evalNum")));
			mv = new ModelAndView("upload_index");
		}
		String userId = CommonUtils.valueOf(request.getParameter("userId"));
		IMap map = sqlServerDao.getEnterpriseAuthority(userId);
		mv.addObject("userId",userId);
		mv.addObject("userAuthority",map.getInt("userAuthority"));
		mv.addObject("username",map.getString("loginUser"));
		return mv;
	}
	
	/**
	 * @param request
	 * @param response
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "getEvalPassEnterpriseInfo", method = RequestMethod.POST)
	@ResponseBody
	public String getEvalPassEnterpriseInfo(HttpServletRequest request, HttpServletResponse response) {
		JSONObject json = new JSONObject();
		try {
			IMap param = new IMap(request); 
			int pageSize = Integer.parseInt(CommonUtils.valueOf(request.getParameter("pageSize")));
			String currentPage = CommonUtils.valueOf(request.getParameter("currentPage"));
			Page page = Page.newBuilder(Integer.parseInt(currentPage),pageSize,null);  
			param.put("page",page);
			
			Map<String,Object> rs = service.getPageData(param);
			page.setTotalRecord(Integer.parseInt(CommonUtils.valueOf(rs.get("totalCount"))));
			List<Map<String,Object>> list = (List<Map<String, Object>>) rs.get("pageData");
			
			json.put("flag", true);
			json.put("datas",list);
			json.put("totalPages",page.getTotalPage());
			json.put("totalData", page.getTotalRecord());
			json.put("currentPage", currentPage);
		} catch (Exception e) {
			if(log.isErrorEnabled()){
				log.error(e.getMessage(),e);
			}
			json.put("flag",false);
		}
		return json.toString();
	}
	
	@RequestMapping(value = "save", method = RequestMethod.POST)
	@ResponseBody
	public String save(HttpServletRequest request, HttpServletResponse response) {
		JSONObject json = new JSONObject();
		try {
			IMap param = new IMap(request); 
			service.save(param);
			json.put("flag", true);
			json.put("msg","保存成功！");
		} catch (Exception e) {
			json.put("flag",false);
			json.put("msg",e.getMessage());
		}
		return json.toString();
	}
	
	@RequestMapping(value = "edit", method = RequestMethod.POST)
	@ResponseBody
	public String edit(HttpServletRequest request, HttpServletResponse response) {
		JSONObject json = new JSONObject();
		try {
			IMap param = new IMap(request); 
			service.edit(param);
			json.put("flag", true);
			json.put("msg","修改成功！");
		} catch (Exception e) {
			if(log.isErrorEnabled()){
				log.error(e.getMessage(),e);
			}
			json.put("flag",false);
			json.put("msg","修改异常！");
		}
		return json.toString();
	}
	
	@RequestMapping(value = "del", method = RequestMethod.POST)
	@ResponseBody
	public String del(HttpServletRequest request, HttpServletResponse response) {
		JSONObject json = new JSONObject();
		try {
			String evalNum = CommonUtils.valueOf(request.getParameter("evalNum"));
			service.del(evalNum);
			json.put("flag", true);
			json.put("msg","删除成功！");
		} catch (Exception e) {
			if(log.isErrorEnabled()){
				log.error(e.getMessage(),e);
			}
			json.put("flag",false);
			json.put("msg","删除异常！");
		}
		return json.toString();
	}
	
	@RequestMapping(value = "query", method = RequestMethod.POST)
	@ResponseBody
	public String query(HttpServletRequest request, HttpServletResponse response) {
		JSONObject json = new JSONObject();
		try {
			String evalNum = CommonUtils.valueOf(request.getParameter("evalNum"));
			json.put("flag", true);
			json.put("datas", service.query(evalNum));
		} catch (Exception e) {
			if(log.isErrorEnabled()){
				log.error(e.getMessage(),e);
			}
			json.put("flag",false);
			json.put("msg","查询异常！");
		}
		return json.toString();
	}
	
	@RequestMapping(value = "importData", method = RequestMethod.POST)
    @ResponseBody
    public String importData(HttpServletRequest request,HttpServletResponse response) throws IOException {
        JSONObject json = new JSONObject();
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        if (multipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            Iterator<String> iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                MultipartFile file = multiRequest.getFile((String)iter.next());
                if (file != null) {
                    try {
                    	Map<String,Object> map = service.importData(file);
                    	json.putAll(map);
                    } catch (Exception e){
                        if(log.isErrorEnabled()){
                            log.error(e.getMessage(),e);
                        }
                        json.put("false",false);
                        json.put("resultInfo","系统异常导致导入失败！");
                    } 
                }
            }
        }
        return json.toString();
    }
	
	@RequestMapping(value = "importIncData", method = RequestMethod.POST)
    @ResponseBody
    public String importIncData(HttpServletRequest request,HttpServletResponse response) throws IOException {
        JSONObject json = new JSONObject();
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        if (multipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            Iterator<String> iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                MultipartFile file = multiRequest.getFile((String)iter.next());
                if (file != null) {
                    try {
                    	Map<String,Object> map = service.importIncData(file);
                    	json.putAll(map);
                    } catch (Exception e){
                        if(log.isErrorEnabled()){
                            log.error(e.getMessage(),e);
                        }
                        json.put("flag",false);
                        json.put("resultInfo","系统异常导致导入失败！");
                    } 
                }
            }
        }
        return json.toString();
    }
	
	@RequestMapping(value = "exportData", method = RequestMethod.POST)
	@ResponseBody
	public String exportData(HttpServletRequest request, HttpServletResponse response) {
		JSONObject json = new JSONObject();
		try {
			String path = CommonUtils.getExportTemplate() + "eval_result_template.xlsx";
			String apply_business = CommonUtils.valueOf(request.getParameter("apply_business"));
			json.put("flag", true);
			json.put("path",service.exportData(path,apply_business));
		} catch (Exception e) {
			if(log.isErrorEnabled()){
				log.error(e.getMessage(),e);
			}
			json.put("flag",false);
		}
		return json.toString();
	}
	
	
	@RequestMapping(value = "uploadFile", method = RequestMethod.POST)
	@ResponseBody
	public String uploadFile(HttpServletRequest request, HttpServletResponse response) {
        JSONObject json = new JSONObject();
        String evalNum = CommonUtils.valueOf(request.getParameter("evalNum"));
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        if (multipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            Iterator<String> iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                MultipartFile multipartFile = multiRequest.getFile((String)iter.next());
                if (multipartFile != null) {
                	json = service.uploadReport(multipartFile,evalNum);
                }
            }
        }
        return json.toString();
    }
	
	@RequestMapping(value = "reportDel", method = RequestMethod.POST)
	@ResponseBody
	public String reportDel(HttpServletRequest request, HttpServletResponse response) {
		JSONObject json = new JSONObject();
		try {
			String evalNum = CommonUtils.valueOf(request.getParameter("evalNum"));
			service.reportDel(evalNum);
			json.put("flag", true);
			json.put("msg","评测报告已删除");
		} catch (Exception e) {
			if(log.isErrorEnabled()){
				log.error(e.getMessage(),e);
			}
			json.put("flag",false);
			json.put("msg","评测报告删除异常");
		}
		return json.toString();
	}
	
	@RequestMapping(value = "downExportFiles")
	public String downExportFiles(HttpServletRequest request, HttpServletResponse response) {
		FileInputStream fs = null;
		OutputStream os = null;
		try {
			String path = request.getParameter("path");
			response.setCharacterEncoding("utf-8");
			response.setHeader("content-disposition","attachment; filename=" + path.substring(path.lastIndexOf(File.separator) + 1, path.length()));
			fs = new FileInputStream(path);
			os = response.getOutputStream();
			int len = 0;
			byte[] b = new byte[1024];
			while ((len = fs.read(b)) != -1) {
				os.write(b, 0, len);
			}
		} catch (Exception e) {
			if(log.isErrorEnabled()) {
				log.error(e.getMessage(),e);
			}
		} finally {
			if (fs != null) {
				try {
					fs.close();
				} catch (IOException e) {
					if(log.isErrorEnabled()) {
						log.error(e.getMessage(),e);
					}
				}
			}
			if (os != null) {
				try {
					os.close();
				} catch (IOException e) {
					if(log.isErrorEnabled()) {
						log.error(e.getMessage(),e);
					}
				}
			}
		}
		return null;
	}
	
	@RequestMapping(value = "downFiles")
	public String downFiles(HttpServletRequest request, HttpServletResponse response) {
		FileInputStream fs = null;
		OutputStream os = null;
		try {
			String type = CommonUtils.valueOf(request.getParameter("type"));
			String fileName = CommonUtils.valueOf(request.getParameter("fileName"));
			String path = "";
			if(StringUtils.equals(type, "template")) {//模板下载
				path = CommonUtils.getExportTemplate();
			}else if (StringUtils.equals(type,"view")){//导入失败查看
				path = CommonUtils.getDataTempPath();
			}else if(StringUtils.equals(type, "report")) {//评测报告下载
				String report = SysProps.getInstance().getValue("eval.report.upload.path");
	    		String[] split = report.split("@");
	    		StringBuffer pathSb = new StringBuffer();
	    		for(String str : split) {
	    			pathSb.append(str).append(File.separator);
	    		}
	    		path = pathSb.toString();
			}
			response.setCharacterEncoding("utf-8");
			response.setHeader("content-disposition","attachment; filename=" + fileName);
			fs = new FileInputStream(path+File.separator+fileName);
			os = response.getOutputStream();
			int len = 0;
			byte[] b = new byte[1024];
			while ((len = fs.read(b)) != -1) {
				os.write(b, 0, len);
			}
		} catch (Exception e) {
			if(log.isErrorEnabled()) {
				log.error(e.getMessage(),e);
			}
		} finally {
			if (fs != null) {
				try {
					fs.close();
				} catch (IOException e) {
					if(log.isErrorEnabled()) {
						log.error(e.getMessage(),e);
					}
				}
			}
			if (os != null) {
				try {
					os.close();
				} catch (IOException e) {
					if(log.isErrorEnabled()) {
						log.error(e.getMessage(),e);
					}
				}
			}
		}
		return null;
	}
}